using System.IO.Compression;
using Keep.Const;
using Keep.Model;
using Keep.Util;
using Serilog;
using SqlSugar;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using Keep.Model.Page;

namespace Keep.Service.Impl
{
    public class FileServiceImpl : IFileService
    {
        private readonly IWebHostEnvironment webHostEnvironment;
        private readonly ILinkService linkService;
        private readonly ILinkTypeService linkTypeService;
        private readonly IMusicListService musicListService;

        public FileServiceImpl(IWebHostEnvironment webHostEnvironment, ILinkService linkService, IMusicListService musicListService, ILinkTypeService linkTypeService)
        {
            this.webHostEnvironment = webHostEnvironment;
            this.linkService = linkService;
            this.musicListService = musicListService;
            this.linkTypeService = linkTypeService;
        }
        //打包下载
        public (string fileType, byte[] archiveData, string archiveName) DownloadFiles(string subDirectory)
        {
            string zipName = $"archive-{DateTime.Now:yyyy_MM_dd-HH_mm_ss}.zip";

            List<string> files = new();
            if (subDirectory.Split('.').Length > 1)
            {
                files.Add(Path.Combine(webHostEnvironment.ContentRootPath, Static.FilePath, subDirectory));
            }
            else
            {
                files = Directory.GetFiles(Path.Combine(webHostEnvironment.ContentRootPath, Static.FilePath, subDirectory)).ToList();
            }

            using MemoryStream memoryStream = new();
            using (ZipArchive archive = new(memoryStream, ZipArchiveMode.Create, true))
            {
                files.ForEach(file =>
                {
                    ZipArchiveEntry theFile = archive.CreateEntry(Path.GetFileName(file));
                    using BinaryWriter binaryWriter = new(theFile.Open());
                    binaryWriter.Write(File.ReadAllBytes(file));
                });
            }
            return ("application/zip", memoryStream.ToArray(), zipName);
        }
        //获取文件所有内容
        public string GetFileData(string staticPath, string name)
        {
            try
            {
                // var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS");
                string realpath = Path.Combine(webHostEnvironment.ContentRootPath, staticPath, name);
                // 检查文件是否存在
                if (File.Exists(realpath))
                {
                    try
                    {
                        // 读取文件所有内容
                        string fileContent = File.ReadAllText(realpath);
                        Log.Information(fileContent);
                        return fileContent;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                    }
                }
                else
                {
                    Log.Information("指定的文件路径不存在");
                    return "指定的文件路径不存在";
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                if (ex.StackTrace != null)
                {
                    Log.Error(ex.StackTrace);
                }
            }
            return "";
        }
        //存储文件所有内容
        public bool SaveFileData(string staticPath, string name, string content)
        {
            try
            {
                // var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS");
                string realpath = Path.Combine(webHostEnvironment.ContentRootPath, staticPath, name);
                // 检查文件是否存在
                if (File.Exists(realpath))
                {
                    try
                    {
                        // 将内容写入目标文件，如果文件存在则覆盖原有内容
                        File.WriteAllText(realpath, content);
                        Log.Information(realpath);
                        return true;
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                    }
                }
                else
                {
                    Log.Information("指定的文件路径不存在");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                if (ex.StackTrace != null)
                {
                    Log.Error(ex.StackTrace);
                }
            }
            return false;
        }
        //获取路径下资源详情
        public PageResult<FileDiy> GetPathInfo(string staticPath, string path, int currentPage, int pageSize)
        {
            PageResult<FileDiy> res = new();
            List<FileDiy> dds = new();
            int retotal = 0;
            try
            {
                // 获取环境变量，比如在开发环境中，可以通过环境变量ASPNETCORE_URLS获取
                // var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS");
                string realpath = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                if (!String.IsNullOrEmpty(path))
                {
                    realpath = Path.Combine(realpath, path);
                }
                DirectoryInfo folder = new(realpath);
                FileSystemInfo[] fileinfo = folder.GetFileSystemInfos();//获取目录下（不包含子目录）的文件和子目录

                fileinfo = fileinfo
                .OrderByDescending(fsi => fsi is DirectoryInfo)  // 将目录排在前面
                .ThenBy(fsi => fsi is DirectoryInfo)  // 如果是目录，则按名称排序
                .ThenBy(fsi => fsi.LastWriteTimeUtc)  // 文件按修改时间排序
                .ToArray();

                retotal = fileinfo.OfType<FileInfo>().Count();
                int ti = 0;//已加载的文件的个数
                int ri = 0;//准备传输的文件个数
                int index = 0;//已加载的文件和文件夹的个数
                foreach (FileSystemInfo i in fileinfo)
                {
                    string fdpath = Path.Combine(Static.ReqUrl, staticPath);
                    if (!String.IsNullOrEmpty(path))
                    {
                        fdpath = Path.Combine(fdpath, path);
                    }
                    fdpath = Path.Combine(fdpath, i.Name);
                    FileDiy dd = new()
                    {
                        index = index,
                        name = i.Name,
                        path = fdpath.Replace("\\", "/"),
                        keypath = String.IsNullOrEmpty(path) ? i.Name : Path.Combine(path, i.Name).Replace("\\", "/"),
                        ctime = i.CreationTime,
                        utime = i.LastWriteTime,
                        isfolder = false,
                    };
                    if (i is DirectoryInfo)
                    {//文件夹
                        dd.isfolder = true;
                        dds.Add(dd);
                        index++;
                    }
                    if (i is FileInfo)
                    {//文件
                        ti++;
                        if (ri >= pageSize)
                        {
                            res.Rows = dds;
                            res.PageNo = currentPage;
                            res.PageSize = pageSize;
                            res.Total = retotal;
                            return res;
                        }
                        if (ti >= (currentPage - 1) * pageSize)
                        {
                            dd.isfolder = false;
                            dd.length = ((FileInfo)i).Length;
                            dd.isimg = false;
                            if (FileUtil.IsImageFile((FileInfo)i))
                            {
                                try
                                {
                                    using var image = SixLabors.ImageSharp.Image.Load(i.FullName);
                                    dd.width = image.Width;
                                    dd.height = image.Height;
                                    dd.isimg = true;
                                    dd.thumbnail = dd.path.Replace(Static.ImgPath, Static.ThumbnailPath);
                                }
                                catch (Exception)
                                {
                                    dd.width = 400;
                                    dd.height = 400;
                                    dd.isimg = true;
                                }
                            }
                            if (realpath.Contains("\\" + Static.FoodPath))
                            {
                                string thpath = Path.Combine(Static.ReqUrl, Static.FoodImgPath, "Thumbnail", i.Name);
                                string newFilename = Path.ChangeExtension(thpath, "jpg");
                                dd.thumbnail = newFilename.Replace("\\", "/");
                            }
                            ri++;
                            dds.Add(dd);
                            index++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                if (ex.StackTrace != null)
                {
                    Log.Error(ex.StackTrace);
                }
            }
            res.Rows = dds;
            res.PageNo = currentPage;
            res.PageSize = pageSize;
            res.Total = retotal;
            return res;
        }
        //获取路径下音乐资源详情
        public PageResult<FileDiy> GetMusicPathInfo(int currentPage, int pageSize)
        {
            PageResult<FileDiy> res = new();
            List<FileDiy> dds = new();
            int retotal = 0;
            try
            {
                string realpath = Path.Combine(webHostEnvironment.ContentRootPath, Static.MusicPath);
                DirectoryInfo folder = new(realpath);
                FileSystemInfo[] fileinfo = folder.GetFileSystemInfos();//获取目录下（不包含子目录）的文件和子目录
                retotal = fileinfo.OfType<FileInfo>().Count();
                int ti = 0;//已加载的文件的个数
                int ri = 0;//准备传输的文件个数
                int index = 0;//已加载的文件和文件夹的个数
                foreach (FileSystemInfo i in fileinfo)
                {
                    string fdpath = Path.Combine(Static.ReqUrl, Static.MusicPath);
                    fdpath = Path.Combine(fdpath, i.Name);
                    string thimg = fdpath.Replace(Static.MusicPath + "\\", Static.MusicImgPath + "\\");
                    string newFilename = Path.ChangeExtension(thimg, "jpg");
                    FileDiy dd = new()
                    {
                        index = index,
                        name = i.Name,
                        path = fdpath.Replace("\\", "/"),
                        thumbnail = newFilename.Replace("\\", "/"),
                        keypath = i.Name,
                        ctime = i.CreationTime,
                        utime = i.LastWriteTime,
                        isfolder = false,
                    };
                    if (i is FileInfo)
                    {//文件
                        ti++;
                        if (ri >= pageSize)
                        {
                            res.Rows = dds;
                            res.PageNo = currentPage;
                            res.PageSize = pageSize;
                            res.Total = retotal;
                            return res;
                        }
                        if (ti >= (currentPage - 1) * pageSize)
                        {
                            dd.isfolder = false;
                            dd.length = ((FileInfo)i).Length;

                            var file = TagLib.File.Create(i.FullName);
                            if (file == null)
                            {
                                Log.Error("无法识别的文件格式" + i.FullName);
                            }
                            else
                            {
                                try
                                {
                                    dd.author = String.IsNullOrEmpty(file.Tag.FirstPerformer) ? "未知艺术家" : file.Tag.FirstPerformer;
                                    dd.totalseconds = file.Properties.Duration.TotalSeconds;
                                }
                                catch (Exception)
                                {
                                }
                            }
                            ri++;
                            dds.Add(dd);
                            index++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                if (ex.StackTrace != null)
                {
                    Log.Error(ex.StackTrace);
                }
            }
            res.Rows = dds;
            res.PageNo = currentPage;
            res.PageSize = pageSize;
            res.Total = retotal;
            return res;
        }

        //文件大小格式转换
        public string SizeConverter(long bytes)
        {
            decimal fileSize = new(bytes);
            decimal kilobyte = new(1024);
            decimal megabyte = new(1024 * 1024);
            decimal gigabyte = new(1024 * 1024 * 1024);

            return fileSize switch
            {
                _ when fileSize < kilobyte => "Less then 1KB",
                _ when fileSize < megabyte => $"{Math.Round(fileSize / kilobyte, 0, MidpointRounding.AwayFromZero):##,###,##}KB",
                _ when fileSize < gigabyte => $"{Math.Round(fileSize / megabyte, 2, MidpointRounding.AwayFromZero):##,###,##}KB",
                _ when fileSize >= gigabyte => $"{Math.Round(fileSize / gigabyte, 2, MidpointRounding.AwayFromZero):##,###,##}KB",
                _ => "n/a"
            };
        }
        //上传文件
        public void UploadFile(List<IFormFile> files, string subDirectory, string staticPath)
        {
            try
            {
                subDirectory ??= string.Empty;
                string target = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                if (!String.IsNullOrEmpty(subDirectory))
                {
                    target = Path.Combine(target, subDirectory);
                }
                Log.Warning(target);
                _ = Directory.CreateDirectory(target);
                if (staticPath.Equals(Static.VideoPath) || staticPath.Equals(Static.BlogPath) || staticPath.Equals(Static.MusicPath) || staticPath.Equals(Static.FoodPath))
                {
                    files.ForEach(file =>
                    {
                        if (file.Length <= 0) { return; }
                        string filePath = Path.Combine(target, file.FileName);
                        using FileStream stream = new FileStream(filePath, FileMode.Create);
                        file.CopyTo(stream);
                    });
                    if (staticPath.Equals(Static.MusicPath))
                    {
                        files.ForEach(file =>
                        {
                            if (file.Length <= 0) { return; }
                            string filePath = Path.Combine(target, file.FileName);
                            var tagfile = TagLib.File.Create(filePath);
                            var pictures = tagfile.Tag.Pictures;
                            if (pictures.Length > 0)
                            {
                                var firstPicture = pictures[0];
                                byte[] imageData = firstPicture.Data.Data;
                                string savePath = filePath.Replace(Static.MusicPath + "\\", Static.MusicImgPath + "\\");
                                string newFilePath = Path.ChangeExtension(savePath, "jpg");
                                System.IO.File.WriteAllBytes(newFilePath, imageData);
                                Log.Information(newFilePath);
                            }
                        });
                    }
                }
                if (staticPath.Equals(Static.ImgPath))
                {
                    files.ForEach(file =>
                    {
                        if (file.Length <= 0) { return; }
                        string filePath = Path.Combine(target, file.FileName);
                        // using FileStream stream = new FileStream(filePath, FileMode.Create);
                        // file.CopyTo(stream);
                        string thumbpath = filePath.Replace(Static.ImgPath, Static.ThumbnailPath);
                        //将图片转换成缩略图,上传到缩略图目录，文件名保持一致，路径一致
                        // CompressImage(filePath,thumbpath);

                        using (var image = Image.Load(file.OpenReadStream()))
                        {
                            image.Save(filePath);
                            // 调整图片大小
                            // image.Mutate(x => x.Resize(200, 200));

                            // 设置 JPEG 编码选项
                            var options = new JpegEncoder
                            {
                                Quality = 5 // 质量范围从 0 到 100，值越大质量越高
                            };

                            // 保存图片
                            image.Save(thumbpath, options);
                        }
                    });
                }
            }
            catch (System.Exception ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
            }
        }
        //上传博客图片
        public string UploadBlogImage(IFormFile file)
        {
            try
            {
                string timepath = DateTime.Now.ToString("yyyy-MM");
                string target = Path.Combine(webHostEnvironment.ContentRootPath, Static.BlogImgPath, timepath);
                Log.Warning(target);
                _ = Directory.CreateDirectory(target);
                string name = Guid.NewGuid().ToString("N") + ".png";
                string filePath = Path.Combine(target, name);
                using FileStream stream = new FileStream(filePath, FileMode.Create);
                file.CopyTo(stream);
                return Path.Combine(Static.ReqUrl, Static.BlogImgPath, timepath, name).Replace("\\", "/");
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return "";
            }
        }
        //上传食谱图片
        public string UploadFoodImage(IFormFile file)
        {
            try
            {
                string timepath = DateTime.Now.ToString("yyyy-MM");
                string target = Path.Combine(webHostEnvironment.ContentRootPath, Static.FoodImgPath, timepath);
                Log.Warning(target);
                _ = Directory.CreateDirectory(target);
                string name = Guid.NewGuid().ToString("N") + ".png";
                string filePath = Path.Combine(target, name);
                using FileStream stream = new FileStream(filePath, FileMode.Create);
                file.CopyTo(stream);
                return Path.Combine(Static.ReqUrl, Static.FoodImgPath, timepath, name).Replace("\\", "/");
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return "";
            }
        }
        //上传食谱封面
        public string UploadFoodThImage(IFormFile file, string name)
        {
            try
            {
                string target = Path.Combine(webHostEnvironment.ContentRootPath, Static.FoodImgPath, "Thumbnail");
                Log.Warning(target);
                _ = Directory.CreateDirectory(target);
                string filePath = Path.Combine(target, name);
                filePath = Path.ChangeExtension(filePath, "jpg");
                using FileStream stream = new FileStream(filePath, FileMode.Create);
                file.CopyTo(stream);
                return Path.ChangeExtension(Path.Combine(Static.ReqUrl, Static.FoodImgPath, "Thumbnail", name), "jpg").Replace("\\", "/");
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return "";
            }
        }
        //上传Icon图片
        public string UploadIconImage(IFormFile file)
        {
            try
            {
                string target = Path.Combine(webHostEnvironment.ContentRootPath, Static.IconImgPath);
                Log.Warning(target);
                _ = Directory.CreateDirectory(target);
                string name = Guid.NewGuid().ToString("N") + ".png";
                string filePath = Path.Combine(target, name);
                using FileStream stream = new FileStream(filePath, FileMode.Create);
                file.CopyTo(stream);
                // return Path.Combine(Static.ReqUrl, Static.IconImgPath, name).Replace("\\", "/");
                return name;
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return "";
            }
        }
        //创建文件
        public bool AddFile(string subDirectory, string staticPath)
        {
            try
            {
                string target = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                if (!String.IsNullOrEmpty(subDirectory))
                {
                    target = Path.Combine(target, subDirectory);
                }
                string filePath = Path.Combine(target, DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".md");
                Log.Warning(filePath);
                // 使用File.Create方法创建一个新文件，如果文件已存在则覆盖
                using FileStream stream = File.Create(filePath);
                // 文件已经创建，FileStream对象在这里可以立即关闭，因为没有写入操作
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return false;
            }
            return true;
        }
        //删除文件
        public bool DelFile(string subDirectory, string staticPath, string name)
        {
            try
            {
                string target = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                if (!String.IsNullOrEmpty(subDirectory))
                {
                    target = Path.Combine(target, subDirectory);
                }
                string filePath = Path.Combine(target, name);
                Log.Information(filePath);
                File.Delete(filePath);
                if (filePath.Contains("keep-back" + @"\" + Static.ImgPath + @"\"))
                {
                    string tfilePath = filePath.Replace(Static.ImgPath, Static.ThumbnailPath);
                    File.Delete(tfilePath);
                }
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return false;
            }
            return true;
        }
        //删除目录及子目录
        public bool DelFileDir(string subDirectory, string staticPath, string name)
        {
            try
            {
                string target = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                if (!String.IsNullOrEmpty(subDirectory))
                {
                    target = Path.Combine(target, subDirectory);
                }
                string filePath = Path.Combine(target, name);
                Log.Information(filePath);
                FileUtil.DeleteDirectoryRecursively(filePath);
                if (filePath.Contains("keep-back" + @"\" + Static.ImgPath + @"\"))
                {
                    string tfilePath = filePath.Replace(Static.ImgPath, Static.ThumbnailPath);
                    FileUtil.DeleteDirectoryRecursively(tfilePath);
                    Log.Information(tfilePath);
                }
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return false;
            }
            return true;
        }
        //创建目录
        public string AddFileDirectory(string subDirectory, string staticPath)
        {
            try
            {
                string target = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                if (!String.IsNullOrEmpty(subDirectory))
                {
                    target = Path.Combine(target, subDirectory);
                }
                string name = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss");
                string filePath = Path.Combine(target, name);
                Log.Information(filePath);
                Directory.CreateDirectory(filePath);
                if (filePath.Contains("keep-back" + @"\" + Static.ImgPath + @"\"))
                {
                    string tfilePath = filePath.Replace(Static.ImgPath, Static.ThumbnailPath);
                    Log.Information(tfilePath);
                    Directory.CreateDirectory(tfilePath);
                }
                return name;
            }
            catch (IOException ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return "";
            }
        }
        //修改目录名称或者修改文件名称
        public bool EditFileDirOrName(string subDirectory, string staticPath, string oldname, string newname)
        {
            try
            {
                string target = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                if (!String.IsNullOrEmpty(subDirectory))
                {
                    target = Path.Combine(target, subDirectory);
                }
                Log.Information(target);
                string oldPath = Path.Combine(target, oldname);
                string newPath = Path.Combine(target, newname);
                Directory.Move(oldPath, newPath);
                Log.Information("目录重命名成功!");
                Log.Information(newPath);
                if (oldPath.Contains("keep-back" + @"\" + Static.ImgPath + @"\"))
                {
                    string tofilePath = oldPath.Replace(Static.ImgPath, Static.ThumbnailPath);
                    string tnfilePath = newPath.Replace(Static.ImgPath, Static.ThumbnailPath);
                    Directory.Move(tofilePath, tnfilePath);
                    Log.Information("目录重命名成功!");
                    Log.Information(tnfilePath);
                }
                if (File.Exists(newPath))
                {
                    if (oldPath.Contains("keep-back" + @"\" + Static.FoodPath + @"\"))
                    {
                        string ftarget = Path.Combine(webHostEnvironment.ContentRootPath, Static.FoodImgPath, "Thumbnail");
                        string thpath = Path.Combine(ftarget, oldname);
                        string oldFilename = Path.ChangeExtension(thpath, "jpg");
                        if (File.Exists(oldFilename))
                        {
                            string th2path = Path.Combine(ftarget, newname);
                            string newFilename = Path.ChangeExtension(th2path, "jpg");
                            Directory.Move(oldFilename, newFilename);
                            Log.Information(newFilename);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                Log.Error(ex.StackTrace);
                return false;
            }
            return true;
        }
        //查询文件通过名称
        public List<FileDiy> SelFileByName(string staticPath, string name)
        {
            List<FileDiy> dds = new();
            try
            {
                // 获取环境变量，比如在开发环境中，可以通过环境变量ASPNETCORE_URLS获取
                string realpath = Path.Combine(webHostEnvironment.ContentRootPath, staticPath);
                dds = GetDirInfo(realpath, "", name, dds);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                if (ex.StackTrace != null)
                {
                    Log.Error(ex.StackTrace);
                }
            }
            return dds;
        }
        //根据路径获取所有文件信息,包含子目录
        public List<FileDiy> GetDirInfo(string currentpath, string ikeypath, string name, List<FileDiy> list)
        {
            DirectoryInfo folder = new(currentpath);
            FileSystemInfo[] files = folder.GetFileSystemInfos();//获取目录下（不包含子目录）的文件和子目录
            if (files != null && files.Length > 0)
            {
                foreach (FileSystemInfo fi in files)
                {
                    string fdpath = Path.Combine(Static.ReqUrl, ikeypath, fi.Name).Replace("\\", "/");
                    if (fi is FileInfo)
                    {
                        if (fi.Name.Contains(name))
                        {
                            FileDiy dd = new()
                            {
                                index = list.Count + 1,
                                name = fi.Name,
                                path = fdpath,
                                keypath = String.IsNullOrEmpty(ikeypath) ? fi.Name : Path.Combine(ikeypath, fi.Name).Replace("\\", "/"),
                                ctime = fi.CreationTime,
                                utime = fi.LastWriteTime,
                                isfolder = false,
                                length = ((FileInfo)fi).Length,
                                isimg = false,
                            };
                            list.Add(dd);
                        }
                    }
                    if (fi is DirectoryInfo)
                    {//文件夹
                        list = GetDirInfo(Path.Combine(currentpath, fi.Name), Path.Combine(ikeypath, fi.Name), name, list);
                    }
                }
            }
            return list;
        }
        //根据静态路径获取路径下文件统计信息
        public List<Statistic> GetPathStatistic()
        {
            List<Statistic> sl = new List<Statistic>();
            List<string> list = new List<string>() { Static.BlogPath, Static.FoodPath, Static.ImgPath, Static.VideoPath, Static.MusicPath };
            try
            {
                Statistic sc0 = new Statistic();
                sc0.name = "Link";
                sc0.flen = 0;
                sc0.dlen = 0;
                List<Links> lls = linkService.SelLinks(new Links());
                if (lls != null && lls.Count > 0)
                {
                    sc0.flen = lls.Count;
                }
                List<LinkType> tls = linkTypeService.SelLinkType();
                if (tls != null && tls.Count > 0)
                {
                    sc0.dlen = tls.Count;
                }
                sl.Add(sc0);
                foreach (string item in list)
                {
                    Statistic sc = new Statistic();
                    sc.dlen = 0;
                    sc.name = item;
                    sc.flen = 0;
                    string realpath = Path.Combine(webHostEnvironment.ContentRootPath, item);
                    sc = GetDirStatistic(realpath, sc);
                    if (item.Equals(Static.MusicPath))
                    {
                        List<MusicList> ml = musicListService.SelMusicList(new MusicList());
                        if (ml != null && ml.Count > 0)
                        {
                            sc.dlen = ml.Count;
                        }
                    }
                    sl.Add(sc);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                if (ex.StackTrace != null)
                {
                    Log.Error(ex.StackTrace);
                }
            }
            return sl;
        }

        //根据路径获取所有文件信息,包含子目录
        public Statistic GetDirStatistic(string currentpath, Statistic sc)
        {
            DirectoryInfo folder = new(currentpath);
            FileSystemInfo[] fileinfo = folder.GetFileSystemInfos();//获取目录下（不包含子目录）的文件和子目录
            if (fileinfo != null && fileinfo.Length > 0)
            {
                foreach (FileSystemInfo fi in fileinfo)
                {
                    if (fi is FileInfo)
                    {//文件
                        sc.flen++;
                    }
                    if (fi is DirectoryInfo)
                    {//文件夹
                        sc.dlen++;
                        sc = GetDirStatistic(Path.Combine(currentpath, fi.Name), sc);
                    }
                }
            }
            return sc;
        }

    }
}
